// webclient
package webclient

import (
	//"log"
	//	"encoding/json"
	"errors"
	"io"
	"net/http"
	"swim/etc"
	"swim/redisclient"
	"swim/request"
	"sync"
	"time"

	//"github.com/garyburd/redigo/redis"
)

type WebClient struct {
	Id              string              //本地会话ID
	Ip              string              //网页IP
	TmpName         string              //临时名称
	ServieLoginId   string              //对方服务端登录的id
	SesionTickCount time.Time           //最近会话时间
	MsgPool         chan request.WebMsg //消息缓存池
	rwLock          sync.RWMutex        //用于web客户端的读写锁
	w               http.ResponseWriter
}

func (c *WebClient) isExpire() bool {
	c.rwLock.RLock()
	defer c.rwLock.RUnlock()
	return time.Now().Sub(c.SesionTickCount) > etc.S_LIFESPAN*time.Second
}

func (c *WebClient) Write(content string) {
	c.rwLock.Lock()
	defer c.rwLock.Unlock()
	c.SesionTickCount = time.Now()
	io.WriteString(c.w, content)
}

//返回false表示队列已满
func (c *WebClient) WriteMsg(content request.WebMsg) bool {
	defer c.UpdateUserTime()
	select {
	case c.MsgPool <- content:
		//do
		return true
	default:
		//warnning!
		return false
	}
	/*
		msgByte, err := json.Marshal(content)
		if err == nil {

			key := c.Id + "_wmsg"
			redisclient.G_redisPool.Get().Do("LPUSH", key, msgByte)
			redisclient.G_redisPool.Get().Do("EXPIRE", key, etc.S_MSG_LIFE_CYCLE)
		} else {
			log.Println(err.Error())
		}
	*/
}

func (c *WebClient) GetMsg() (request.WebMsg, error) {
	defer c.UpdateUserTime()
	var msg request.WebMsg
	select {
	case msg = <-c.MsgPool:
		return msg, nil
	case <-time.After(time.Second * etc.S_QUERY_MSG_TIME):
		//log.Println("time out!!!")
		return msg, errors.New("time out")
	}
	/*
		key := c.Id + "_wmsg"
		msgArrayObj, err := redisclient.G_redisPool.Get().Do("BRPOP", key, etc.S_QUERY_MSG_TIME)
		//msgArrayObj, err := redisclient.G_redisPool.Get().Do("RPOP", key)
		if err == nil {
			msgObj, bConfirm := msgArrayObj.([]interface{})
			if bConfirm {
				msgByte, bIsBytes := msgObj[1].([]byte)
				if bIsBytes {
					jErr := json.Unmarshal(msgByte, &msg)
					return msg, jErr
				}
				return msg, errors.New("parse msg error")
			}
		}
		return msg, err
	*/
}

func (c *WebClient) UpdateUserTime() {
	c.rwLock.Lock()
	c.SesionTickCount = time.Now()
	c.rwLock.Unlock()
}

func (c *WebClient) DelMsgKey() {
	key := c.Id + "_wmsg"
	redisclient.G_redisPool.Get().Do("DEL", key)
}

func (c *WebClient) CheckSendTooMuch() bool {
	if time.Now().Sub(c.SesionTickCount) < etc.S_MIN_SEND_MSG_TIME*time.Second {
		return true
	}
	return false
}
